package com.wosai.register.security;

import java.io.IOException;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.GenericFilterBean;

import com.wosai.register.util.SecurityUtil;

public class RestAuthenticationTokenProcessingFilter extends GenericFilterBean {
    private static final Log logger = LogFactory.getLog(RestAuthenticationTokenProcessingFilter.class);

    private final AuthenticationManager authenticationManager;
    
    @Autowired
    public RestAuthenticationTokenProcessingFilter(AuthenticationManager authenticationManager)
    {
        this.authenticationManager = authenticationManager;
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException,
                         ServletException
    {
        String token = request.getParameter("security_token");
        if (token != null) {
            String[] fields = SecurityUtil.decodeToken(token);
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(fields[0], fields[1]);
            authRequest.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest)request));
            
            // Alternatively, custom validate against the user details service.
            Authentication authResult = this.authenticationManager.authenticate(authRequest);
            
            SecurityContextHolder.getContext().setAuthentication(authResult);
        }

        chain.doFilter(request, response);
    }

}
